<template>
  <el-card >
    <div slot="header" class="clearfix">
      <h4>跨区域转货申请单-新增</h4>
    </div>
    <el-row>
      <skus-table
        showSelectCol
        showActionCol
        :table-height="500"
        :data-source="tableInfo.list"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :selectionChange="selectionChange"
        :actionColWidth="80"
        :actionRender="renderTableBtnAction"
      >
        <el-row slot="content_context" type="flex" justify="end">
          <el-button
            :disabled="noData"
            :loading="autoLoading"
            type="primary"
            size="mini"
            @click="getReceiveCompany"
            >自动获取收货公司</el-button
          >
          <el-button
            :disabled="noData"
            type="primary"
            size="mini"
            @click="emptyGoodsForNotReceive"
            >清空未选择收货公司的商品</el-button
          >
          <el-tooltip>
            <ul slot="content" class="tooltip">
              <li>可清空的商品：</li>
              <li>1.收货区域消化天数大于365天;</li>
              <li>2.收货区域 无销售;</li>
              <li>3.发起区域消化天数小于收货区域。</li>
            </ul>
            <el-button
              :disabled="noData"
              type="primary"
              size="mini"
              @click="emptyGoodsForAbnormal"
              >清空消化天数异常的商品</el-button
            >
          </el-tooltip>
          <el-button
            :disabled="noSelect"
            type="primary"
            size="mini"
            @click="selectReceiveCompany"
            >选择收货公司</el-button
          >
          <el-button
            :disabled="noData"
            type="primary"
            size="mini"
            @click="validIsExceedUpperLimit"
            >提交</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleGoBack"
            >返回</el-button
          >
        </el-row>
      </skus-table>
      <SelectCompanyDialog :companyVisible.sync="companyVisible" :selectIds="selectIds" @setTransferNum="setTransferNum"/>
    </el-row>
  </el-card>
</template>
<script>
import SkusTable from '@/components/skusTable';
import SelectCompanyDialog from './components/SelectCompanyDialog'
import {
  queryTransferDataService,
  selectTransferCompanyService,
  submitTransferDataService,
  computeDigestionDaysService,
  validIsExceedUpperLimitService
} from '@api/stock/stockOverflow';

export default {
  components: {
    SkusTable,
    SelectCompanyDialog
  },
  data () {
    return {
      companyVisible: false,
      autoLoading: false,
      submitLoading: false,
      tableInfo: {
        list: [],
        selection: [],
        columns: [
          {
            title: 'SKU编码',
            key: 'skuNo',
          },
          {
            title: '商品名称',
            key: 'productName',
          },
          {
            title: '规格',
            key: 'specialDetail',
          },
          {
            title: '计量单位',
            key: 'unitName',
          },
          {
            title: '件装数量',
            key: 'pieceAmount',
            width: 90
          },
          {
            title: '可售库存数量',
            key: 'canSendAmount',
            width: 100
          },
          {
            title: '下限',
            key: 'startCompanyLowerLimit',
          },
          {
            title: '上限',
            key: 'startCompanyUpperLimit',
          },
          {
            title: '本公司预计消化天数',
            key: 'planDigestionDays',
            width: 140
          },
          {
            title: '成本价',
            key: 'costPrice',
          },
          {
            title: '仓位',
            key: 'stockName',
          },
          {
            title: '本区域预计消化天数',
            key: 'areaPrepareCostDays',
            width: 140
          },
          {
            title: '本区域近三月销量',
            key: 'areaThreeMonthsOut',
            width: 120
          },
          {
            title: '本区域近一年销量',
            key: 'transferAreaYearOut',
            width: 120
          },
          {
            title: '收货公司',
            key: 'receiveCompanyName',
          },
          {
            title: '收货公司下限',
            key: 'lowerLimit',
            width: 100
          },
          {
            title: '收货公司上限',
            key: 'upperLimit',
            width: 100
          },
          {
            title: '可转货数量',
            key: 'canTransferNum',
            width: 100
          },
          {
            title: '转货数量',
            key: 'transferNum',
            width: 160,
            render: (h, { row }) => {
              return <el-input-number onChange={() => { this.transferNumChange(row) }} controls={ false } v-model={row.transferNum} min={0} max={row.canSendAmount} precision={row.decimalPlaces} />
            }
          },
          {
            title: '转货金额',
            key: 'transterAmount',
          },
          {
            title: '收货区域近三月销量',
            key: 'receiveAreaThreeMonthsOut',
            width: 130
          },
          {
            title: '收货区域近一年销量',
            key: 'receiveAreaYearOut',
            width: 130
          },
          {
            title: '收货区域可售库存',
            key: 'receiveAreaCanSendAmout',
            width: 120
          },
          {
            title: '收货区域采购在途',
            key: 'areaOnPurchase',
            width: 120
          },
          {
            title: '收货区域转货在途',
            key: 'areaTransferTotal',
            width: 120
          },
          {
            title: '收货区域现库存加转货数量消化天数',
            key: 'newPlanDigestionDays',
            width: 220
          },
          {
            title: '处理备注',
            key: 'processRemark',
          }
        ],
        loading: false
      },
      ids: [],
      ERRORS_COLUMN: {
        title: '禁止提交原因',
        key: 'errorMsg',
        fixed: 'left',
        width: '130',
        sortable: true,
        errorTip: true,
        notShowTip: true,
      }
    };
  },
  computed: {
    noData () {
      return this.tableInfo.list.length === 0;
    },
    noSelect () {
      return this.tableInfo.selection.length === 0;
    },
    selectIds () {
      return this.tableInfo.selection.map(item => (item.id))
    }
  },
  created () {
    const { idList } = this.$route.params;
    this.ids = idList || [];
    this.getTableData();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row, index }) {
      return <div>
        <el-button type="text" onClick={() => { this.handleDelete(row, index) }}>删除</el-button>
      </div>
    },
    handleDelete (row, index) {
      this.tableInfo.list.splice(index, 1)
    },
    transferNumChange (row) {
      this.getComputeResult([row]).then((res) => {
        const { newPlanDigestionDays, transterAmount } = res[0];
        row.newPlanDigestionDays = newPlanDigestionDays;
        row.transterAmount = transterAmount;
      })
    },
    // 勾选需要处理的库存
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    async getComputeResult (data) {
      const res = await computeDigestionDaysService(data, state => { this.tableInfo.loading = state })
      if (res?.retData) {
        return res.retData;
      }
    },
    async getTableData () {
      const res = await queryTransferDataService(this.ids, state => { this.tableInfo.loading = state })
      if (res?.retData) {
        const { detailList } = res.retData;
        this.tableInfo.list = detailList;
      }
    },
    // 自动获取收货公司
    async getReceiveCompany () {
      const res = await selectTransferCompanyService(this.ids, state => { this.autoLoading = state })
      if (res?.retData) {
        this.tableInfo.list = res.retData;
      }
    },
    // 清空未选择收货公司的商品
    emptyGoodsForNotReceive () {
      this.tableInfo.list = this.tableInfo.list.filter(item => item.receiveCompanyId)
      console.log(this.tableInfo.list)
    },
    // 清空消化天数异常的商品  1、收货区域消化天数大于365天 2、收货区域 无销售。 3、发起区域消化天数小于收货区域。
    emptyGoodsForAbnormal () {
      this.tableInfo.list = this.tableInfo.list.filter(item => {
        if (item.receiveCompanyId) {
          return item.newPlanDigestionDays &&
                  item.newPlanDigestionDays != '无销售' &&
                  parseInt(item.newPlanDigestionDays) <= 365 &&
                  parseInt(item.planDigestionDays) > parseInt(item.newPlanDigestionDays)
        }
        return item;
      })
    },
    // 选择收货公司
    selectReceiveCompany () {
      this.companyVisible = true;
    },
    // 根据收货公司生成表格数据
    setTransferNum (list) {
      this.getComputeResult(list).then((res) => {
        const ids = list.map(item => item.id)
        this.tableInfo.list = this.tableInfo.list.filter(item => !ids.includes(item.id)).concat(res)
      })
    },
    // 校验是否存在上限
    async validIsExceedUpperLimit () {
      const res = await validIsExceedUpperLimitService(this.tableInfo.list, state => { this.submitLoading = state })
      if (res.retData) {
        this.$confirm(`${res.retData}`, '提示', {
          confirmButtonText: '仍要转货',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleSubmit()
        }).catch(() => {});
      } else {
        this.handleSubmit()
      }
    },
    // 提交
    async handleSubmit () {
      const res = await submitTransferDataService(this.tableInfo.list, state => { this.submitLoading = state })
      if (res.retData) {
        this.$alert('存在禁止提交原因，无法提交单据，请在详情页中查看具体原因', '提交错误提示', {
          confirmButtonText: '确定',
          type: 'warning',
        });
        const hasErrorColumn = this.tableInfo.columns.some(item => item.key == 'errorMsg')
        if (!hasErrorColumn) {
          this.tableInfo.columns.unshift(this.ERRORS_COLUMN)
        }
        this.tableInfo.list = res.retData;
      } else {
        this.$message.success('提交成功')
        this.handleGoBack()
      }
    },
    handleGoBack () {
      this.$router.push({ name: 'stockOverflow', query: { processingStatus: ['3'], processingType: '7' } })
    }
  }
};
</script>
